#!/usr/bin/env python
# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

baseurl = "http://repository.wine-cellar.googlecode.com/hg/"

import os
import logging
import tarfile
from lxml import etree
from time import time

logger = logging.getLogger('build_packlist')
hdlr = logging.FileHandler('build_packlist.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)


def cleanup(cwd):
    os.system("rm -fR /tmp/tmp_pack")
    os.chdir(cwd)

repository = etree.Element("Repository")
repository.attrib['version'] = "0.1"
etree.SubElement(repository, "name").text = "WineCellar repository"
owner = etree.SubElement(repository, "owner")
owner.text = "Samuel Taylor"
owner.attrib['email'] = "samtaylor.uk@gmail.com"
etree.SubElement(repository, "updated").text = '"'+str(time())+'"'
etree.SubElement(repository, "mirror").text = baseurl


for filename in os.listdir('packages'):
    basename, extension = os.path.splitext(filename)
    if extension == ".wcp":
        
        logger.info("Extracting: "+filename)
        print "Extracting: "+filename
        os.makedirs("/tmp/tmp_pack")
        cwd = os.getcwd()
        os.chdir("/tmp/tmp_pack")
        try:
            tar = tarfile.open(cwd+"/packages/"+filename, "r")
	    files = tar.getmembers()
	    for item in files:
        	tar.extract(item)
        except:
            logger.error("Unable to extract: "+filename)
            print "Unable to extract: "+filename
            cleanup(cwd)
            continue
        
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str("control.xml"), parser)
        
        for element in tree.iter("Wine"):
            packageType = "wine"
            logger.debug("Wine package")
            break
        else:
            for element in tree.iter("Application"):
                shortname = element.find("shortname").text
                description = element.find("description").text
                msLicense = element.find("ms-license").text
                category = element.find("category").text
                icon = element.find("icon").text
                packageType = "application"
                logger.debug("Application package")
                break
            else:
                logger.error("Corrupt control.xml for "+filename)
                print "Corrupt control.xml for "+filename
                cleanup(cwd)
                continue
        
        name = element.find("name").text
        version = tree.find("version").text
        vendor = tree.find("vendor").text
        homepage = tree.find("homepage").text
        licenseName = tree.find("license").attrib['name']
        licenseAddress = tree.find("license").text
        
        if packageType == "wine":
            for element in repository.iter("Wine"):
                if element.find("name").text == name:
                    package = element
                    break
            else:
                package = etree.SubElement(repository, "Wine")
                etree.SubElement(package, "name").text = name
                etree.SubElement(package, "vendor").text = vendor
                etree.SubElement(package, "homepage").text = homepage
                license = etree.SubElement(package, "license")
                license.text = licenseAddress
                license.attrib['name'] = licenseName
        else:
            for element in repository.iter("Application"):
                if element.find("shortname").text == shortname:
                    package = element
                    break
            else:
                package = etree.SubElement(repository, "Application")
                etree.SubElement(package, "name").text = name
                etree.SubElement(package, "shortname").text = shortname
                etree.SubElement(package, "vendor").text = vendor
                etree.SubElement(package, "homepage").text = homepage
                
                os.chdir(cwd+"/packages/icons")
                try:
                    tar = tarfile.open("/tmp/tmp_pack/data.tar.bz2", "r")
                    tar.extract(icon)
                except:
                    logger.error("Unable to extract icon: "+filename)
                    print "Unable to extract icon: "+filename
                os.chdir("/tmp/tmp_pack")
               
                etree.SubElement(package, "icon").text = icon
                etree.SubElement(package, "description").text = description
                etree.SubElement(package, "ms-license").text = msLicense
                etree.SubElement(package, "category").text = category
                license = etree.SubElement(package, "license")
                license.text = licenseAddress
                license.attrib['name'] = licenseName

        pack = etree.SubElement(package, "package")
        pack.text = filename
        pack.attrib['version'] = version
        
        cleanup(cwd)
        
f = open(str("packages/index.xml"), 'w')
logger.debug("Creating XML")
f.write(etree.tostring(repository, pretty_print=True, encoding='iso-8859-1'))
f.close()
